from django.shortcuts import render, HttpResponse
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json
from app01 import models
from django import forms
from app01.utils.form import BootStrapModelForm
from app01.utils.pagination import Pagination


class TaskModelForm(BootStrapModelForm):
    class Meta:
        model = models.Task
        fields = '__all__'


def task_list(request):
    """任务列表"""
    # 去数据库获取所有任务
    query_set = models.Task.objects.all().order_by('-id')
    page_obj = Pagination(request, query_set)

    form = TaskModelForm()
    context = {
        'form': form,
        'queryset': page_obj.page_queryset,
        'page_str': page_obj.html(),
    }

    return render(request, 'task_list.html', context)


# 免除csrf_token验证
@csrf_exempt
def task_ajax(request):
    # print(request.GET)
    print(request.POST)
    data_dict = {
        'status': True,
        'data': [10, 11, 12]
    }
    return HttpResponse(json.dumps(data_dict))

    # return JsonResponse(data_dict)


@csrf_exempt
def task_add(request):

    # 1. 用户发送过来的数据进行校验(ModelForm)
    form = TaskModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        data_dict = {'status': True}
        return HttpResponse(json.dumps(data_dict))
    # print(form.errors.as_json(), type(form.errors))
    data_dict = {'status': False, 'error': form.errors}
    return HttpResponse(json.dumps(data_dict, ensure_ascii=False))
